const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;
const session = require('./session');
const config = require('./config');
const rs = require('./log');
const code = require('./code');
// const api = require('./lib/tk_sdk/index');
// const commins = require('./request');
const help = require('./service');
var callback = {
    //窗口内容发生变化
    onWindowChange: function (event, arg) {
        session.getToken();
    },
    //获取cookie
    onGetSession: function (event) {
        if (global.cookies.length < 1) {
            this.onWindowChange();
        }
    },
    //获取系统信息
    onGetOsInfo: function (event, arg) {
        var os = require('os');
        var osInfo = {
            arch: os.arch(),//CPU处理器架构
            cpus: os.cpus(),//获取cpu信息
            //空闲内存字节
            freemem: os.freemem(),
            //当前登录用户的根目录
            homedir: os.homedir(),
            //操作系统主机名
            hostname: os.hostname(),
            //网络配置列表
            networkInterfaces: os.networkInterfaces(),
            //操作系统类型, 返回值有'darwin', 'freebsd', 'linux', 'sunos' , 'win32'
            platform: os.platform(),
            //操作系统版本
            release: os.release(),
            //操作系统临时文件的默认目录
            tmpdir: os.tmpdir(),
            //系统总内存
            totalmem: os.totalmem(),
            //操作系统名称，基于linux的返回linux, 基于苹果的返回Darwin, 基于windows的返回Windows_NT
            type: os.type(),
            //计算机正常运行时间
            uptime: os.uptime()
        };
        event.sender.send('onRecv_getOs', osInfo);
    },
    //创建新的窗口
    createWindow: function (url, w, h) {
        w = w || 800;
        h = h || 600;
        if (!url) {
            return false;
        }
        var win = new BrowserWindow({
            width: w, height: h,
            autoHideMenuBar: true,
            maxWidth: 1200,
            maxHeight: 800,
            resizable: false,
            maximizable: false,
            title: '',
            minimizable: false,
            allowDisplayingInsecureContent: true,
            skipTaskbar: false,
            useContentSize: true,
            type: 'desktop',
            show: false
        })
        win.loadURL(url);
        return win;
    },
    //打开新的窗口
    onOpenWindw: function (event) {

    },
    //登录
    login:function (event,name,pwd) {
        if(!name || !pwd){

        }
        var loginBrow = BrowserWindow.fromId(global.loginWindow);

        loginBrow.close();
    },
    //登录阿里妈妈
    tkLogin: function (event, data) {
        if (global.tk_is_login) {
            help.showAlert('当前已登录阿里账号');
            event.sender.send('onRecv_tkLogin', 1);
            return false;
        }
        var win = callback.createWindow(global.login_url, 800, 600);
        win.show();
        var webContents = win.webContents;
        global.childWindow = win.id;
        win.on('closed', function () {
            event.sender.send('onRecv_tkLogin', 1);
            global.childWindow = null;
        });
    },
    //隐藏登录窗口
    minLogin: function () {
        if (!global.childWindow) return false;
        var loginBrow = BrowserWindow.fromId(global.childWindow);
        var topBrow = BrowserWindow.fromId(global.topWindow);
        loginBrow.hide();
        topBrow.focus();
    },
    //获取淘宝授权
    accessToken: function (event, a) {
        if (typeof a === 'object') {
            var win = callback.createWindow(config.ali_access_url, a.w, a.h);
            win.show();
            var webContents = win.webContents;
            global.childWindow = win.id;
            win.on('closed', function () {
                global.childWindow = null;
            });
            webContents.on('did-get-redirect-request', function (e, old, newUrl) {
                if (newUrl.search('#access_token=') != -1) {
                    session.getToken();
                    var index = newUrl.indexOf('#');
                    var tokens = newUrl.substring(index + 1);
                    var obj = tokens.split('&');
                    for (var i = 0; i < obj.length; i++) {
                        if (obj[i].length < 1) {
                            continue;
                        }
                        if (obj[i].indexOf('=') != -1) {
                            var temp = obj[i].split('=');
                            global.access_token[temp[0]] = temp[1];
                        }
                    }
                    win.close();
                    rs.createLog(global.access_token);
                }
            });
        }
    },
    //申请高佣
    applfCommis: function (event, adzone) {
        if (global.start_applf) {
            help.showAlert('不要点了啦，人家已经在申请了。。。。');
            return false;
        }
        callback.process(event, adzone);
    },
    //创建子进程进行高佣申请
    process: function (event, map) {
        var cookies = global.cookies.tk_cookie;
        if(!cookies) {
            help.showErr('请先登录阿里账号后操作');
            return false;
        }
        const spawn = require('child_process').fork;
        const child = spawn(__dirname + '/request.js');

        global.procss = child;
        child.on('message', function (m) {
            if (typeof m === 'object') {
                switch (m.code) {
                    case code.login :
                        global.tk_is_login = false;
                        global.cookies.tk_cookie = null;
                        help.showErr('请重新登录阿里账号');
                        break;
                    case code.reay_applf :
                        global.start_applf = true;
                        break;
                    case code.applfLoding :
                        event.sender.send('onRecv_applfCommis',m.data);
                        break;
                    case code.convert :
                        event.sender.send('onRecv_applfCommis',m.data);
                        break;
                    default:
                        console.log(m);
                }
            }
        });
        child.on('close', function (code) {
            global.start_applf = false;
            global.procss = null;
        });
        child.send({name: 'applfCommins', 'value': {cookie:cookies,ad:map}});
    },
    //终止高佣申请
    stopProcess: function (event) {
        if (!global.procss) {
            return false;
        }
        global.procss.send({name: 'closed'});
    }
};
module.exports = callback;